package com.hoyue.common.utils;

import com.hoyue.system.bean.Role;
import com.hoyue.system.bean.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.security.Principal;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class ShiroUtils {

    @Autowired
    private static SessionDAO sessionDAO;

    /**
     * 获取当前用户Subject信息
     * @return
     */
    public static Subject getSubjct() {
        //获取用户session(如果当前用户没有常见session的话,true则创建一个并返回,false为返回null)
        return SecurityUtils.getSubject();
    }

    /**
     * 获取用户Email
     * @return 返回邮箱字符串
     */
    public static String getUserEmail() {
        Object object = getSubjct().getPrincipal();
        return object.toString();
    }

    /**
     * 获取用户信息
     * @return
     */
    public static User getUser() {
        User user = (User) ShiroSessionUtils.getShiroAttribute("user");
        // Object object = getSubjct().getPrincipal();
        return user;
    }

    /**
     * 获取用户id
     * @return
     */
    public static Integer getUserId() {
        return getUser().getId();
    }

    public static void logout() {
        getSubjct().logout();
    }

    public static List<Principal> getPrinciples() {
        List<Principal> principals = null;
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        return principals;
    }

    /**
     * 获取用户角色名
     * @return
     */
    public static Set<Role> getRoles() {
        Set<Role> roles = (Set<Role>) ShiroSessionUtils.getShiroAttribute("roles");
        return roles;
    }

    /**
     * 获取用户权限标识
     * @return
     */
    public static Set<String> getPermissions() {
        return (Set<String>) ShiroSessionUtils.getShiroAttribute("permissions");
    }
}
